package com.android.fastride.model.http.intercepter;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.android.fastride.exception.ResponseException;
import com.android.fastride.model.http.entity.CommonResponse;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 对api进行拦截的拦截器
 * Created by pengyuantao on 2017/9/26 9:58.
 * NOTE:需要注意，这个拦截器只能拦截api，关于上传下载相关的，不要使用这个拦截器
 */

public class ApiInterceptor implements Interceptor {

    private static final String TAG = "ApiInterceptor";

    //json的数据类型
    private static final String TYPE_JSON = "json";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        String json = response.body().string();
        Log.i(TAG, "intercept: " + json);
        //这个可能抛出Json解析异常，由于使用Retrofit和Rxjava直接让他抛
        CommonResponse comResponse = JSON.parseObject(json, CommonResponse.class);

        if (comResponse == null) {
            throw new ResponseException(response.code(), response.message());
        }

        int code = comResponse.getCode();
        if (code == CommonResponse.RESULT_OK) {
            //将用户关心的数据进行返回
            Response.Builder responseBuilder = response.newBuilder();
            responseBuilder.body(ResponseBody.create(response.body().contentType(), comResponse
					.getResult()));
            return responseBuilder.build();
        } else {
            String message = comResponse.getMsg();
            throw new ResponseException(code, message);
        }
    }

}
